﻿using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;

namespace Digitalmes.AvaloniaUI.ViewModels;

public sealed partial class IconViewModel : ViewModelBase
{
    // Icon 资源 Key 以 "_regular" 结尾。
    public string[] Icons => Application.Current!.Resources
        .Where(r => r.Key is string s && s.EndsWith("_regular"))
        .Select(r => r.Key.ToString()!).ToArray();

    // 复制文本到剪贴板。
    [RelayCommand]
    private async Task CopyText(string? text, CancellationToken token)
    {
        try
        {
            await DoSetClipboardTextAsync(text);
        }
        catch
        {
        }
    }

    private async Task DoSetClipboardTextAsync(string? text)
    {
        // For learning purposes, we opted to directly get the reference
        // for StorageProvider APIs here inside the ViewModel. 

        // For your real-world apps, you should follow the MVVM principles
        // by making service classes and locating them with DI/IoC.

        // See DepInject project for a sample of how to accomplish this.
        if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop ||
            desktop.MainWindow?.Clipboard is not { } provider)
            throw new NullReferenceException("Missing Clipboard instance.");

        await provider.SetTextAsync(text); // 文本为 null 时剪贴板将被清除。
    }
}
